package com.sf.fy.uav.applet.order.controller.task;

import com.sf.fy.uav.common.request.order.task.GoodsSoundRecordingRequest;
import com.sf.fy.uav.good.controller.GoodsSoundRecordingRest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.File;
import java.util.Iterator;

/**
 * @author LTQ
 */
@RestController
@RequestMapping("/home/upload/")
public class UploadFileRest {


    @Autowired
    private GoodsSoundRecordingRest goodsSoundRecordingRest;


    @Value("${file.path:/usr/local/applet/}")
    private String baseUrl;


    @PostMapping("record")
    @CrossOrigin
    public String uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String name = request.getParameter("name");
        String duration = request.getParameter("duration");
        String goodsTypeId = request.getParameter("goodsTypeId");
        String taskId = request.getParameter("taskId");
        String fileName = request.getParameter("fileName");
        String displayOrder = request.getParameter("displayOrder");
        GoodsSoundRecordingRequest goodsSoundRecordingRequest = new GoodsSoundRecordingRequest();
        goodsSoundRecordingRequest.setName(name);
        goodsSoundRecordingRequest.setDuration(Long.valueOf(duration));
        goodsSoundRecordingRequest.setTaskId(taskId);
        goodsSoundRecordingRequest.setFileName(fileName);
        goodsSoundRecordingRequest.setDisplayOrder(Integer.valueOf(displayOrder));
        goodsSoundRecordingRest.add(goodsSoundRecordingRequest);
        String fileSavePath = baseUrl + "goods/record/";
        //设置编码
        request.setCharacterEncoding("utf-8");
        File dir = new File(fileSavePath);
        System.out.println(dir.getPath());
        //创建一个名为当前年月日的文件夹，在文件夹中存放图片
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formData的值
            Iterator<String> iterator = req.getFileNames();

            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                //真正写到磁盘上
                File file1 = new File(fileSavePath + fileName);
                file.transferTo(file1);
                System.out.println(file1.getPath());
            }
        } catch (Exception e) {
        }
        return fileSavePath;
    }


}